<template>
  <div class="attachTable">
    <div class="edit-table-toolbar">
      <div>{{ title }}</div>
      <div class="edit-btn" v-if="!hideBtn">
        <template v-for="(i, index) in btnConfig">
          <el-button
            class="btn-text-blue"
            size="mini"
            :key="index"
            v-if="showBtn(i.name)"
            :icon="i.icon"
            @click="i.methons"
          >{{ i.text }}</el-button>
        </template>
      </div>
    </div>
    <div class="edit-table-content">
      <el-table
        :data="tableData"
        border
        stripe
        ref="attachTable"
        :header-cell-style="headerStyle"
        :max-height="tableConfig.maxHeight || 400"
      >
        <el-table-column v-if="tableConfig.select" type="selection" fixed="left" width="40"></el-table-column>
        <el-table-column type="index" width="55" label="序号"></el-table-column>
        <template v-for="(item, index) in tableConfig.column">
          <el-table-column :label="item.label" :width="item.width" :prop="item.prop" :key="index">
            <template slot-scope="scope">
              {{
              item.formatter
              ? item.formatter(scope.row)
              : scope.row[scope.column.property]
              }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button
              @click="preItem(scope.row)"
              v-show="showPreBtn(scope.row)"
              type="text"
              size="small"
              title="预览"
              icon="el-icon-view"
            ></el-button>
            <el-button
              @click="downItem(scope.row)"
              type="text"
              v-if="scope.row.id"
              size="small"
              title="下载"
              icon="el-icon-download"
            ></el-button>
            <el-button
              @click="deleteItem(scope.row)"
              v-if="scope.row.id && !hideBtn"
              type="text"
              size="small"
              title="删除"
              icon="el-icon-delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <dialogPublic
      :title="'附件上传'"
      :show.sync="show"
      @doSubmit="addToTable"
      class="attachTable--dialog"
      appendTobody
      @doClose="() => (show = false)"
    >
      <el-upload
        class="upload-demo"
        action
        :auto-upload="false"
        drag
        multiple
        :file-list="fileList"
        :on-remove="fileChange"
        :on-change="fileChange"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
      </el-upload>
    </dialogPublic>
    <dialogPublic
      :title="'文件预览'"
      :show.sync="showPreview"
      appendTobody
      fullscreen
      noFootBtn
      @doClose="() => (showPreview = false)"
    >
      <preview :fileObj="currentAttach" v-if="showPreview"></preview>
    </dialogPublic>
  </div>
</template>
<script>
// 导入组件
import preview from "@/components/attach/preview";
import {
  uploadAttach, //附件上传
  deleteFiles, //删除单个附件通过文件id
  deleteFilesType, //删除附件通过业务id,业务类型
  getAttachList //附件列表获取
} from "@/api/common";
export default {
  props: {
    attachSetting: {
      type: Object,
      default: () => {
        return { businessId: "", businessType: "" };
      }
    },
    hideBtn: {
      type: Boolean,
      default: false
    }
  },
  components: { preview },
  data() {
    return {
      title: "表格标题",
      tableConfig: {
        select: true,
        data: [],
        column: [
          {
            label: "文件名",
            prop: "name"
            // width: 150,
          },
          {
            label: "扩展名",
            prop: "extension",
            width: 100
          },
          {
            label: "上传状态",
            prop: "state",
            width: 100,
            formatter: row => {
              return row.id ? "上传成功" : "等待上传";
            }
          },
          {
            label: "上传人",
            prop: "createByName"
            // width: 150,
          },
          {
            label: "上传时间",
            prop: "createTime"
            // width: 150,
          }
        ]
      },
      btnConfig: [
        {
          name: "add",
          text: "添加",
          icon: "el-icon-plus",
          methons: () => {
            this.add();
          }
        },
        {
          name: "download",
          text: "下载",
          icon: "el-icon-download",
          methons: () => {
            this.download();
          }
        },
        {
          name: "delete",
          text: "删除",
          icon: "el-icon-delete",
          methons: () => {
            this.delete();
          }
        },
        {
          name: "save",
          text: "上传附件",
          icon: "el-icon-check",
          methons: () => {
            this.save();
          }
        }
      ],
      //文件分类
      typeObj: {
        imge: ["jpg", "jpeg", "gif", "bmp", "png"],
        pdf: ["pdf"],
        video: ["mp4", "m2v", "mkv", "rmvb", "wmv", "avi", "flv", "mov", "m4v"],
        html: ["htm", "html"],
        docx: ["doc", "docx", "docm", "dotx", "dotm"],
        xlsx: ["xls", "xlsx", "xlsm", "xltx", "xltm", "xlsb", "xlam"],
        // txt:["txt"],
        pptx: ["ppt", "pptx", "pot", "potx", "pptm", "ppsx", "ppsm"],
        zip: ["zip", "rar", "7z", "7-zip", "tar", "gzip", "bz2", "jar"]
      },
      tableData: [],
      currentId: "",
      newFileArr: [],
      btnArr: [],
      fileList: [],
      deleteIdArr: [], //删除的附件ID
      show: false,
      showPreview: false, //文件预览
      showPdf: false,
      maxFileSize: 50, //可上传的文件的最大size,50M
      preurl: "", //预览URL
      htmlText: "预览转换中。。。"
    };
  },
  watch: {
    //监听页面标识变化
    "attachSetting.businessId"(val) {
      // let fragment = this.attachSetting.fragment;
      if (val) {
        this.getFileList();
      }
    }
    // "attachSetting.businessType"(val) {
    //   let fragment = this.attachSetting.fragment;
    //   if (val && fragment) {
    //     //所绑定的同一个businessId的一部分附件，businessType必须
    //     this.getFileList();
    //   }
    // }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      let { btnArr, title, data, select, businessId } = this.attachSetting;
      this.btnArr = btnArr || [];
      this.title = title || "";
      this.tableConfig.data = data || [];
      this.tableConfig.select = select;
      this.currentId = businessId;
      this.tableConfig.data.map((i, index) => {
        i.rowIndex = index;
      });
      if (businessId) {
        this.getFileList();
      }
    },
    headerStyle() {
      return {
        borderRight: "none"
      };
    },
    showBtn(btn) {
      return this.btnArr.indexOf(btn) != -1;
    },
    //获取附件列表数据
    getFileList() {
      let { businessId, businessType } = this.attachSetting;
      let form = {
        businessId: businessId,
        businessType: businessType
      };
      getAttachList(form).then(res => {
        this.newFileArr = [];
        let data = res.data || [];
        this.tableData = data;
      });
    },
    add() {
      this.show = true;
      this.fileList = [];
    },
    //关闭预览弹窗
    doClose() {
      this.showPdfViewer = false;
      this.showPdf = false;
    },
    //文件改变时
    fileChange(file, fileList) {
      //添加的附件
      this.fileList = fileList;
    },
    //是否显示预览按钮
    showPreBtn(row) {
      let typeArr = ["jpg", "jpeg", "gif", "bmp", "png", "pdf"];
      if (row.id && row.path) {
        return true;
        // if (row.path) {
        //   return true;
        // } else {
        //   return typeArr.includes(row.extension);
        // }
      } else {
        return false;
      }
    },
    //点击预览
    async preItem(file) {
      let { extension, path } = file;
      let type = "";
      for (const key in this.typeObj) {
        //循环遍历typeObj
        let arr = this.typeObj[key];
        if (arr.includes(extension)) {
          //比较找到typeObj相应的后缀名，从而判断它属于哪个类型
          type = key;
        }
      }
      if (["imge", "pdf", "video", "html"].includes(type)) {
        this.currentAttach = file;
        this.showPreview = true;
      } else {
        this.$confirm(`该文件暂不支持预览，是否直接下载？`, "提示", {
          confirmButtonText: "立即下载",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.downItem(file);
        });
      }
    },
    // 点击下载
    downItem(row) {
      this.$utils.downloadFile(row.id, row.name);
    },
    // 关闭查看器
    closeViewer() {
      this.showViewer = false;
    },
    //点击新增
    addToTable() {
      this.newFileArr = [];
      this.fileList.map(i => {
        //处理新添加的附件，把附件数据添加到已有的表格数据内
        let { name, raw, size } = i;
        let pathStep = name.lastIndexOf("."); //取到文件名开始到最后一个点的长度
        let pathLen = name.length; //取到文件名长度
        let type = name.substring(pathStep + 1, pathLen); //获取文件类型
        let obj = {
          name: name, //附件名
          extension: type //附件类型
        };
        this.tableData.push(obj);
        this.newFileArr.push(raw);
      });
      // this.save();
      this.show = false;
    },
    //点击删除
    delete() {
      let selectRow = this.$refs.attachTable.selection; //选中的附件所在的行
      this.tableConfig.data = [...this.tableConfig.data].filter(x =>
        [...selectRow].every(y => {
          if (y.rowIndex == x.rowIndex) {
            if (y.id) {
              this.deleteIdArr.push(y.id); //把选中删除的附件ID存起来
            }
            return false;
          } else {
            return true;
          }
        })
      );
    },
    //按照项删除(立即删除)
    deleteItem(data) {
      //一项一项的删除就立即调用删除接口
      this.$confirm("此操作将删除【" + data.name + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteFiles(data.id)
            .then(res => {
              this.getFileList();
              this.$message.success("文件删除成功！");
            })
            .catch(e => {
              this.$message.warning("文件删除失败！");
            });
        })
        .catch(e => {});
    },
    //删除附件通过业务id,业务类型（立即删除）
    deleteTypeFiles() {
      let form = {
        businessId: this.attachSetting.businessId,
        businessType: this.attachSetting.businessType
      };
      deleteFilesType(form)
        .then(res => {
          this.getFileList();
        })
        .catch(e => {
          //console.log(e);
        });
    },
    //点击保存（上传）
    save() {
      let { businessId, businessType } = this.attachSetting;
      let fileObj = this.newFileArr;
      let formData = new FormData();
      if (businessId && fileObj.length) {
        fileObj.map(i => {
          formData.append("files", i);
        });
        let form = {
          businessId, //单据id
          businessType //单据id
        };
        uploadAttach(form, formData)
          .then(res => {
            this.newFileArr = [];
            this.getFileList();
            // this.$message.success("保存成功！");
          })
          .catch(res => {
            this.$message.warning("文件上传失败,请重新上传！");
          });
        this.show = false;
      }
    },
    //下载
    download() {
      let selectRow = this.$refs.attachTable.selection;
      selectRow.map(i => {
        if (i.attachmentUrl) {
          let fileName = i.attachmentName + "." + i.extension;
          this.$utils.downloadFile(i.attachmentUrl, fileName);
        }
      });
    },
    //获取表单数据
    getFormData() {
      let { data } = this.tableConfig;
      let newData = {
        deleteId: this.deleteIdArr.join(),
        data: data
      };
      return newData;
    },
    //给表单赋值
    setTableData(data) {
      this.deleteIdArr = [];
      data = JSON.parse(JSON.stringify(data));
      data.map((i, index) => (i.rowIndex = index));
      this.$set(this.tableConfig, "data", [...data]);
    }
  }
};
</script>
<style scoped>
.edit-table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}
</style>
<style lang="less">
.attachTable--dialog {
  border: 1px solid #e1e1e1;
  margin-bottom: 10px;
  .upload-demo .el-upload {
    width: 100%;
    text-align: center;
    .el-upload-dragger {
      display: inline-block;
    }
  }
}
.attachTable {
  .el-table .el-table__cell {
    padding: 5px 0px;
  }
  .el-table .el-table__header-wrapper td,
  .el-table .el-table__header-wrapper th {
    border-right: 1px solid #ebeef5 !important;
  }
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #ebeef5 !important;
  }
}
</style>
